<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang=en lang=en>
<HEAD>
	<meta http-equiv=content-type content="text/html; charset=utf-8" />
	<link rel=stylesheet href="http://www.cs.usfca.edu/~parrt/lecture-wiki.css" type="text/css" />
<title>StringTemplate Documentation</title>
</HEAD>
<BODY>
<H1>StringTemplate Documentation</H1>


<P>Brought to you by that maniac that brings you the
<A HREF="http://www.antlr.org"><B> ANTLR parser generator</B></A>!

<P>Terence Parr <BR>
University of San Francisco <BR>
<TT>parrt at cs.usfca.edu</TT> <BR>
<em>Copyright 2003-2005</em> <BR>
<A HREF="http://www.stringtemplate.org"><B>http://www.stringtemplate.org</B></A> <BR>
(StringTemplate released under BSD License)

<P><em>Version 2.3 coming Summer 2006</em>

<P>Please see the <A HREF="http://www.stringtemplate.org/bugs.tml"><B> changes and bugs</B></A> page.

<P>Note that the <TT>TestStringTemplates.java</TT> file has many tests that are
an excellent set of examples.  Also, I highly recommend you read the
(academically-oriented) paper,
<A HREF="http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf"><B> Enforcing
Model-View Separation in Template Engines</B></A>.  There are some more
examples including nested menu generation that will be of interest.
<H2>Introduction</H2>


<P>Most programs that emit source code or other text output are
unstructured blobs of generation logic interspersed with print
statements. The primary reason is the lack of suitable tools and
formalisms. The proper formalism is that of an output grammar because
you are not generating random characters--you are generating sentences
in an output language. This is analogous to using a grammar to
describe the structure of input sentences. Rather than building a
parser by hand, most programmers will use a parser
generator. Similarly, we need some form of <em>unparser generator</em> to
generate text. The most convenient manifestation of the output grammar
is a template engine such as <TT>StringTemplate</TT>.

<P>A template engine is a simply a code generator that emits text using
templates, which are really just "documents with holes" in them where
you can stick values.  <TT>StringTemplate</TT> breaks up your template into
chunks of text and attribute expressions, which are by default
enclosed in dollar signs <TT>$</TT><em>attribute-expression</em><TT>$</TT> (to make them
easy to see in HTML files).  <TT>StringTemplate</TT> ignores everything
outside of attribute expressions, treating it as just text to spit out
when you call <TT>StringTemplate.toString()</TT>.  For example, the following
template has two chunks, a literal and a reference to attribute
<TT>name</TT>:

<div class="code"><PRE>
Hello, $name$
</PRE></div>



<P>Using templates in Java code is very easy. Here is the requisite example that prints "<TT>Hello, World</TT>":

<div class="code"><PRE>
StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());
</PRE></div>



<P><TT>StringTemplate</TT> is not a "system" or "engine" or "server"; it's a
library with two primary classes of interest: <TT>StringTemplate</TT> and
<TT>StringTemplateGroup</TT>.  You can directly create a <TT>StringTemplate</TT> in
Java code, you can load a template from a file, and you can load a
single file with many templates (a template group file).
<H2>Motivation And Philosophy</H2>


<P><TT>StringTemplate</TT> was born and evolved during the development of
<A HREF="http://www.jGuru.com"><B>http://www.jGuru.com</B></A>.  The need for such dynamically-generated web
pages has led to the development of numerous other template engines in
an attempt to make web application development easier, improve
flexibility, reduce maintenance costs, and allow parallel code and
HTML development.  These enticing benefits, which have driven the
proliferation of template engines, <B>derive entirely from a single
principle</B>: separating the specification of a page's business logic
and data computations from the specification of how a page displays
such information.  These template engines are in a sense are a
reaction to the completely entangled specifications encouraged by JSP
(Java Server Pages).  With separate encapsulated specifications,
template engines promote component reuse, pluggable site "looks",
single-points-of-change for common components, and high overall system
clarity.  In the code generation realm, model-view separation
guarantees retargetability.

<P>When developing StringTemplate, I recalled Frederick Brook's book,
"Mythical Man Month", where he identified <em>conceptual integrity</em> as a
crucial product ingredient.  For example, in UNIX everything is a
stream.  My concept, if you will, is <em>strict model-view separation</em>.
My mission statement is therefore:
<BLOCKQUOTE>
"<i>StringTemplate shall be as simple, consistent, and powerful as
possible without sacrificing strict model-view separation.</i>"</BLOCKQUOTE>



<P>I ruthlessly evaluate all potential features and functionality against
this standard.  Over the years, however, I have made certain
concessions to practicality that one could consider as infringing
ever-so-slightly into potential model-view entanglement.  That said,
StringTemplate still seems to enforce separation while providing
excellent functionality.

<P>I let my needs dictate the language and tool feature set.  The tool
evolved as my needs evolved.  I have done almost no feature
"backtracking".  Further, I have worked really hard to make this
little language self-consistent and consistent with existing
syntax/metaphors from other languages.  There are very few special
cases and attribute/template scoping rules make a lot of sense even if
they are unfamiliar or strange at first glance.  Everything in the
language exists to solve a very real need.

<P>After examining hundreds of template files that I created over years
of jGuru.com (and now in ANTLR v3) development, I found that I needed
only the following four basic canonical operations (with some
variations):
<UL>
<LI>attribute reference; e.g., <TT>$phoneNumber$</TT>
</LI>
<LI>template reference (like #include or macro expansion); e.g., <TT>$searchbox()$</TT>
</LI>
<LI>conditional include of subtemplate (an IF statement); e.g., <TT>$if(title)$&lt;title&gt;$title$&lt;/title&gt;$endif$</TT>
</LI>
<LI>template application to list of attributes; e.g., <TT>$names:bold()$</TT>
</LI>

</UL>

<P>where template references can be recursive.  

<P>Language theory supports my premise that even a minimal StringTemplate
engine with only these features is very powerful--such an engine can
generate the context-free languages (see
<A HREF="http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf"><B> Enforcing
Strict Model-View Separation in Template Engines</B></A>); e.g., most
programming languages are context-free as are any XML pages
whose form can be expressed with a DTD.

<P>The normal imperative programming language features like setting
variables, loops, arithmetic expressions, arbitrary method calls into
the model, etc... are not only unnecessary, but they are very
specifically what is wrong with JSP.  Recall that JSP allows arbitrary
Java expressions and statements, allowing programmers to incorporate
computations and logic in their templates.  A quick scan of template
engines reveals an unfortunate truth--all but a few are
Turing-complete languages just like JSP.  One can argue that they are
worse than JSP because they use languages peculiar to that template
engine.  Many tool builders have clearly lost sight of the original
problem we were all trying to solve.  We programmers often get caught
up in cool implementations, but we should focus on what <B>should</B> be
built not what <B>can</B> be built.

<P>The fact that StringTemplate does not allow such things as assignments
(no side-effects) should make you suspicious of engines that do allow
it.  I guarantee that the templates in ANTLR v3's code generator are
vastly more complicated than any web page, for example, created for
use with another template engine and I have yet to find a situation
where I needed assignments.  If your template looks like a program, it
probably is--you have totally entangled your model and view.

<P>While providing all sorts of dangerous features like assignment that
promote the use of computations and logic in templates, many engines
miss the key elements.  Certain language semantics are absolutely
required for generative programming and language translation.  One is
<em>recursion</em>.  A template engine without recursion seems unlikely to be
capable of generating recursive output structures such as nested
tables or nested code blocks.

<P>Another distinctive <TT>StringTemplate</TT> language feature lacking in other
engines is <em>lazy-evaluation</em>.  <TT>StringTemplate</TT>'s attributes are
lazily evaluated in the sense that referencing attribute "<TT>a</TT>" does
not actually invoke the data lookup mechanism until the template is
asked to render itself to text.  Lazy evaluation is surprising useful
in both the web and code generation worlds because such order
decoupling allows code to set attributes when it is convenient or
efficient not necessarily before a template that references those
attributes is created.  For example, a complicated web page may
consist of many nested templates many of which reference <TT>$userName$</TT>,
but the value of <TT>userName</TT> does not need to be set by the model until
right before the entire page is rendered to text via <TT>toString()</TT>.
You can build up the complicated page, setting attribute values in any
convenient order.

<P><TT>StringTemplate</TT> implements a "poor man's" form of lazy evaluation by
simply requiring that all attributes be computed <em>a priori</em>.  That is,
all attributes must be computed and pushed into a template before it
is written to text; this is the so-called "<em>push method</em>" whereas most
template engines use the "<em>pull method</em>".  The pull method appears
more conventional because programmers mistakenly regard templates as
programs, but pulling attributes introduces <em>order-of-computation
dependencies</em>.  Imagine a simple web page that displays a list of
names (using some mythical template engine notation):

<div class="code"><PRE>
&lt;html&gt;
&lt;body&gt;
&lt;ol&gt;
$foreach n in names$
  &lt;li&gt;$n$&lt;/li&gt;
$end$
&lt;/ol&gt;
There are $numberNames$ names.
&lt;/body&gt;
&lt;/html&gt;
</PRE></div>



<P>Using the pull method, the reference to <TT>names</TT> invokes
<TT>model.getNames()</TT>, which presumably loads a list of names from the
database.  The reference to <TT>numberNames</TT> invokes
<TT>model.getNumberNames()</TT> which necessarily uses the internal data
structure computed by <TT>getNames()</TT> to compute <TT>names.size()</TT> or
whatever.  Now, suppose a designer moves the <TT>numberNames</TT> reference
to the <TT>&lt;title&gt;</TT> tag, which is <B>before</B> the reference to <TT>names</TT> in
the <TT>foreach</TT> statement.  The names will not yet have been loaded,
yielding a null pointer exception at worst or a blank title at best.
You have to anticipate these dependencies and have <TT>getNumberNames()</TT>
invoke <TT>getNames()</TT> because of a change in the template.  I'm stunned
that other template engine authors with whom I've spoken think this is
ok.  Any time I can get the computer to do something automatically for
me that removes an entire class of programming errors, I'll take it!
Automatic garbage collection is the obvious analogy here.

<P>The pull method requires that programmers do a topological sort in
their minds anticipating any order that a programmer or designer could
induce.  To ensure attribute computation safety (i.e., avoid hidden
dependency landmines), I have shown trivially in my academic paper
that <em>pull</em> reduces to <em>push</em> in the worst case.  With a complicated
mesh of templates, you will miss a dependency, thus, creating a really
nasty, difficult-to-find bug.

<P>Just so you know, I've never been a big fan of functional languages
and I laughed really hard when I realized (while writing the academic
paper) that I had implemented a functional language.  The nature of
the problem simply dictated a particular solution.  We are generating
sentences in an output language so we should use something akin to a
grammar.  Output grammars are inconvenient so tool builders created
template engines.  Restricted template engines that enforce the
universally-agreed-upon goal of strict model-view separation also look
remarkably like output grammars as I have shown.  So, the very nature
of the language generation problem dictates the solution: a template
engine that is restricted to support a mutually-recursive set of
templates with side-effect-free and order-independent attribute
references.
<H2>Defining Templates</H2>

<H3>Creating Templates With Java Code</H3>


<P>Here is a simple piece of Java that creates and uses a template on the fly:

<div class="code"><PRE>
StringTemplate query =
  new StringTemplate("SELECT $column$ FROM $table$;");
query.setAttribute("column", "name");
query.setAttribute("table", "User");
</PRE></div>



<P>where <TT>StringTemplate</TT> considers anything in <TT>$...$</TT> to be something
it needs to pay attention to.  By setting attributes, you are
"pushing" values into the template for use when the template is
printed out.  The attribute values are set by referencing their names.
Invoking <TT>query.toString()</TT> would yield

<div class="code"><PRE>
SELECT name FROM User;
</PRE></div>



<P>You can set an attribute multiple times, which simply means that the
attribute is multi-valued.  For example, adding another
<TT>setAttribute()</TT> call makes attribute <TT>column</TT> multi-valued:

<div class="code"><PRE>
StringTemplate query =
  new StringTemplate("SELECT $column$ FROM $table$;");
query.setAttribute("column", "name");
query.setAttribute("column", "email");
query.setAttribute("table", "User");
</PRE></div>



<P>Invoking <TT>query.toString()</TT> would now yield

<div class="code"><PRE>
SELECT nameemail FROM User;
</PRE></div>



<P>Ooops...there is no separator between the multiple values.  If you want a comma, say, between the column names, then change the template to record that formatting information:

<div class="code"><PRE>
StringTemplate query =
  new StringTemplate("SELECT $column; separator=\",\"$ FROM $table$;");
query.setAttribute("column", "name");
query.setAttribute("column", "email");
query.setAttribute("table", "User");
</PRE></div>



<P>Note that the right-hand-side of the separator specification in this case is a string literal; therefore, I have escaped the double-quotes as the template is specified in a Java string.  In general, the right-hand-side can be any attribute expression.  Invoking <TT>query.toString()</TT> would now yield

<div class="code"><PRE>
SELECT name,email FROM User;
</PRE></div>



<P>Attributes can be any object at all.  <TT>StringTemplate</TT> calls <TT>toString()</TT> on each object as it writes the template out.  The separator is not used unless the attribute is multi-valued.
<H3>Loading Templates From Files</H3>


<P>To load a template from the disk you must use a <TT>StringTemplateGroup</TT>
that will manage all the templates you load, caching them so you do
not waste time talking to the disk for each template fetch request
(you can change it to not cache; see below).  You may have multiple
template groups.  Here is a simple example that loads the previous SQL
template from file <TT>/tmp/theQuery.st</TT>:

<div class="code"><PRE>
SELECT $column; separator=","$ FROM $table$;
</PRE></div>



<P>The Java code creates a <TT>StringTemplateGroup</TT> called <TT>myGroup</TT> rooted
at <TT>/tmp</TT> so that requests for template <TT>theQuery</TT> forces a load of
file <TT>/tmp/theQuery.st</TT>.

<div class="code"><PRE>
StringTemplateGroup group =
  new StringTemplateGroup("myGroup", "/tmp");
StringTemplate query = group.getInstanceOf("theQuery");
query.setAttribute("column", "name");
query.setAttribute("column", "email");
query.setAttribute("table", "User");
</PRE></div>



<P>If you have a directory hierarchy of templates such as file
<TT>/tmp/jguru/bullet.st</TT>, you would reference them relative to the root;
in this case, you would ask for template <TT>jguru/bullet()</TT>.

<P><B>Note</B>: StringTemplate strips whitespace from the front and back of
all loaded template files.  You can add, for example, <TT>&lt;\n&gt;</TT> at the
end of the file to get an extra carriage return.
<H3>Loading Templates From CLASSPATH</H3>


<P>When deploying applications or providing a library for use by other programmers, you will not know where your templates files live specifically on the disk.  You will, however, know relative to the classpath where your templates reside.  For example, if your code is in package <TT>com.mycompany.server</TT> you might put your templates in a <TT>templates</TT> subdirectory of <TT>server</TT>.  If you do not specify an absolute directory with the <TT>StringTemplateGroup</TT> constructor, future loads via that group will happen relative to the <TT>CLASSPATH</TT>.  For example, to load template file <TT>page.st</TT> you would do the following:

<div class="code"><PRE>
// Look for templates in CLASSPATH as resources
StringTemplateGroup group = new StringTemplateGroup("mygroup");
StringTemplate st = group.getInstanceOf("com/mycompany/server/templates/page");
</PRE></div>



<P>If <TT>page.st</TT> references, say, <TT>searchbox</TT> template, it must be fully qualified as:

<div class="code"><PRE>
&lt;font size=2&gt;SEARCH&lt;/font&gt;: $com/mycompany/server/templates/page/searchbox()$
</PRE></div>



<P>This is inconvenient and I may add the invoking template's path prefix automatically in the future.
<H2>StringTemplate Group Files</H2>


<P><TT>StringTemplate</TT> 2.0 introduced the notion of a group file that has
two main attractions.  First, it allows you to define lots of small
templates more conveniently because they may all be defined within a
single file.  Second, you may specify formal template arguments that
help <TT>StringTemplate</TT> detect errors (such as setting unknown
attributes) and make the templates easier to read.  Here is a sample
group file (I'm using <TT>&lt;...&gt;</TT> delimiters) with two templates, <TT>vardef</TT>
and <TT>method</TT>, that could be used to generate C files:

<div class="code"><PRE>
group simple;

vardef(type,name) ::= "&lt;type&gt; &lt;name&gt;;"

method(type,name,args) ::= &lt;&lt;
&lt;type&gt; &lt;name&gt;(&lt;args; separator=","&gt;) {
  &lt;statements; separator="\n"&gt;
}
&gt;&gt;
</PRE></div>



<P>Single line templates are enclosed in double quotes while multi-line templates are enclosed in double angle-brackets. Every template must define arguments even if the formal argument list if blank.

<P>Using templates in a group file is straightforwards.  A <TT>StringTemplateGroup</TT> constructor accepts a <TT>Reader</TT> so you can pass in a string or file or whatever:

<div class="code"><PRE>
String templates =
   "group simple; vardef(type,name) ..."; // templates from above
StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates));
StringTemplate t = group.getInstanceOf("vardef");
t.setAttribute("type", "int");
t.setAttribute("name", "foo");
System.out.println(t);
</PRE></div>



<P>The output would be: "<TT>int foo;</TT>".
<H3>Formal argument default values</H3>


<P>Sometimes it is convenient to have default values for formal arguments
that are used when no value is set by the model.  For example, when
generating a parser in Java from ANTLR, I want the super class of the
generated object to be <TT>Parser</TT> unless the ANTLR user uses an option
to set the super class to some custom class.  For example, here is a
partial <TT>parser</TT> template definition:

<div class="code"><PRE>
parser(name, rules, superClass="Parser") ::= ...
</PRE></div>



<P>Any argument may be given a default value by following the name with
an equals sign and a string or an anonymous template.
<H3>Formal argument error handling</H3>


<P>When using a group file format to specify templates, you must specify
the formal arguments for that template.  If you try to set an
attribute via <TT>setAttribute</TT> that is not specifically formally defined
in that template, you will get a <TT>NoSuchElementException</TT>.

<P>If you reference an attribute that is not formally defined in that
template or any enclosing template, you also get a
<TT>NoSuchElementException</TT> exception.
<H3>Maps</H3>


<P>There are situations where you need to translate a string in one
language to a string in another language.  For example, you might want
to translate <TT>integer</TT> to <TT>int</TT> when translating Pascal to C.  You
could pass a <TT>Map</TT> (hashtable) from the model into the templates, but
then you have output literals in your model!  The only solution is to
have <TT>StringTemplate</TT> support mappings.  For example, here is how
ANTLR v3 knows how to initialize local variables to their default
values:

<div class="code"><PRE>
typeInitMap ::= [
        "int":"0",
        "long":"0",
        "float":"0.0",
        "double":"0.0",
        "boolean":"false",
        "byte":"0",
        "short":"0",
        "char":"0",
        default:"null" // anything other than an atomic type
]
</PRE></div>



<P>To use the map in a template, refer to it as you would an attribute.
For example, <TT>&lt;typeInitMap.int&gt;</TT> which returns "0".  If your type name
is an attribute not a constant like <TT>int</TT>, then use an indirect field
access: <TT>&lt;typeInitMap.(typeName)&gt;</TT>.

<P>Maps are defined in the group's scope and are visible if no attribute
hides them.  For example, if you define a formal argument called
<TT>typeInitMap</TT> in template <TT>foo</TT> then <TT>foo</TT> cannot see the map defined
in the group (though you could pass it in as another parameter).  If a
name is not an attribute and it's not in the group's maps table, then
the super group is consulted etc...  You may not redefine a map and it
may not have the same name as a template in that group.  The <TT>default</TT>
value is used if you use a key as a property that doesn't exist.  For
example <TT>&lt;typeInitMap.foo&gt;</TT> returns "<TT>null</TT>".

<P>You'll note that the square brackets will denote <em>data structure</em> in
other areas too such as <TT>[a,b,c,...]</TT> which makes a singe multi-valued
attribute out of other attributes so you can iterate across them.
<H3>Newline handling</H3>


<P>The first newline following the <TT>&lt;&lt;</TT> in a template definition is
ignored as it is usually used just to get the first line of text for
the template at the start of a line.  In other words, if you want to
have a blank line at the start of your template, use:

<div class="code"><PRE>
foo() ::= &lt;&lt;

2nd line is not blank, but first is
&gt;&gt;
</PRE></div>



<P>or

<div class="code"><PRE>
foo() ::= &lt;&lt;&lt;\n&gt;
same as before; newline then this line
&gt;&gt;
</PRE></div>



<P>The last newline before the <TT>&gt;&gt;</TT> is also ignored and is not included in
the output.  To add a final newline, add an extra line or <TT>&lt;\n&gt;</TT>
before the <TT>&gt;&gt;</TT>:

<div class="code"><PRE>
foo() ::= &lt;&lt;
rodent

&gt;&gt;
</PRE></div>



<P>or

<div class="code"><PRE>
foo() ::= &lt;&lt;
rodent&lt;\n&gt;
&gt;&gt;
</PRE></div>



<P>Template:

<div class="code"><PRE>
foo() ::= &lt;&lt;
rodent
&gt;&gt;
</PRE></div>



<P>on the other hand, is identical to

<div class="code"><PRE>
foo() ::= "rodent"
</PRE></div>


<H3>Group file format</H3>


<div class="code"><PRE>
group
    :	"group" ID ';' (template|mapdef)*
    ;

template
    :	ID '(" (args)? ')' "::=" TEMPLATE
    |   ID "::=" ID // alias one template to be another
    ;

args:	arg (',' arg)*
    ;

arg :   ID '=' STRING             // "..."
    |   ID '=' ANONYMOUS_TEMPLATE // {...}
    ;

mapdef
    : ID "::=" map
    ;

map :   '[' keyValuePair (',' keyValuePair)* ']'
    ;

keyValuePair
    :   STRING ':' STRING
    |   "default" ':' STRING
    ;
</PRE></div>



<TABLE cellspacing=0 border=1>
<TR><TD><B>An aside</B>: All along, during my website construction days, I kept in mind that any text output follows a format and, thus, output sentences conform to a language.  Consequently, a grammar should describe the output rather than a bunch of ad hoc print statements in code.  This helped me formalize the study of templates because I could compare templates (output grammars) to well established ideas from formal language theory and context-free grammars.  This allowed me to show, among other things, that <TT>StringTemplate</TT> can easily generate any document describable with an XML DTD even though it is deliberately limited.  The group file format should look very much like a grammar to you.
</TD></TR>
</TABLE>


<P>See the scoping rules section for information on how formal arguments affect attribute look up.

<P>I use <TT>.stg</TT> file extension, which you might also want to use.
<H2>Functionality</H2>

<H3>Attribute References</H3>

<H4>Named attributes</H4>


<P>The most common thing in a template besides plain text is a simple named attribute reference such as:

<div class="code"><PRE>
Your email: $email$
</PRE></div>



<P>The template will look up the value of <TT>email</TT> and insert it into the output stream when you ask the template to print itself out.  If <TT>email</TT> has no value, then it evaluates to the empty string and nothing is printed out for that attribute expression.
<H4>Property references</H4>


<P>If a named attribute is an aggregate with a property (ala JavaBeans)
or a simple data field, you may reference that property using
<em>attribute</em>.<em>property</em>.  For example:

<div class="code"><PRE>
Your name: $person.name$
Your email: $person.email$
</PRE></div>



<P><TT>StringTemplate</TT> ignores the actual object type stored in attribute
<TT>person</TT> and simply invokes <TT>getName()</TT> and <TT>getEmail()</TT> via
reflection.  As a special case, StringTemplate tries <TT>x.isFoo()</TT> for
<TT>x.foo</TT> if <TT>x</TT> is <TT>Boolean</TT>.

<P>If the property is not accessible ala JavaBeans, <TT>StringTemplate</TT>
attempts to find a field with the property name.  In the above
example, <TT>StringTemplate</TT> would look for fields <TT>name</TT> and <TT>email</TT>
without the capitalization used with JavaBeans property access
methods.

<P>Because the type is ignored, you can pass in whatever existing Java
aggregate (class) you have such as <TT>User</TT> or <TT>Person</TT>:

<div class="code"><PRE>
User u = database.lookupPerson("parrt@jguru.com");
st.setAttribute("person", u);
</PRE></div>



<P>Or, if a suitable aggregate doesn't exist, you can make a connector or "glue" object and pass that in instead:

<div class="code"><PRE>
st.setAttribute("person", new Connector());
</PRE></div>



<P>where <TT>Connector</TT> is defined as:

<div class="code"><PRE>
public class Connector {
    public String getName() { return "Terence"; }
    public String getEmail() { return "parrt@jguru.com"; }
}
</PRE></div>



<P>The ability to reference aggregrate properties saves you the trouble
of having to pull out the properties with Java code like this:

<div class="code"><PRE>
User u = database.lookupPerson("parrt@jguru.com");
st.setAttribute("name", u.getName());
st.setAttribute("email", u.getEmail());
</PRE></div>



<P>and having template:

<div class="code"><PRE>
Your name: $name$
Your email: $email$
</PRE></div>



<P><B>Warning</B>: The latter is more widely applicable and totally decoupled
from code and logic; i.e., it's "better" but much less convenient.  Be
very careful that the property methods do not have any side-effects
like updating a counter or whatever.  This breaks the rule of order of
evaluation independence.
<H5>Indirect property names</H5>


<P>Sometimes the property name is itself in which case you need to use
indirect property access notation:

<div class="code"><PRE>
$person.(propertyName)$
</PRE></div>



<P>where <TT>propertyName</TT> is an attribute whose value is the name of a
property to fetch from <TT>person</TT>.  Using the examples from above,
<TT>propertyName</TT> could hold the value of either <TT>name</TT> or <TT>email</TT>.

<P><TT>propertyName</TT> may actually be an expression instead of a simple
attribute name.
<H5>Map key/value pair access</H5>


<P>You may pass in instances of type <TT>HashMap</TT> and <TT>Hashtable</TT> but cannot
pass in objects implementing the <TT>Map</TT> because that would allow all
sorts of wacky stuff like database access.   Rather than creating an
aggregate object (though I make it easier for you with the automatic
aggregate creation in the next section) you can pass in a <TT>HashMap</TT>
that has keys referencable within templates.  For example, 

<div class="code"><PRE>
StringTemplate a = new StringTemplate("$user.name$, $user.phone$");
HashMap user = new HashMap();
user.put("name", "Terence");
user.put("phone", "none-of-your-business");
a.setAttribute("user", user);
String results = a.toString();
</PRE></div>



<P>yields a result of "<TT>Terence, none-of-your-business</TT>".
<H4>Automatic aggregate creation</H4>


<P>Creating one-off data aggregates in Java is a pain, you have to define
a new class just to associate two pieces of data.  <TT>StringTemplate</TT>
makes it easy to group data during <TT>setAttribute()</TT> calls.  You may
pass in an aggregrate attribute name to <TT>setAttribute()</TT> with the data
to aggregate:

<div class="code"><PRE>
StringTemplate st =
        new StringTemplate("$items:{$it.last$, $it.first$\n}$");
st.setAttribute("items.{first,last}", "John", "Smith");
st.setAttribute("items.{first,last}", "Baron", "Von Munchhausen");
String expecting =
        "Smith, John\n" +
        "Von Munchhausen, Baron\n";
</PRE></div>



<P>Note that the template, <TT>st</TT>, expects the <TT>items</TT> to be aggregates with properties <TT>first</TT> and <TT>last</TT>.  By using attribute name

<div class="code"><PRE>
items.{first,last}
</PRE></div>



<P>You are telling <TT>StringTemplate</TT> to take the following two arguments as properties <TT>first</TT> and <TT>last</TT>.  

<P>I have created variants of the <TT>setAttribute()</TT> method to handle from
2 to 5 properties.  This is really handy, at least for Java. :)
<H4>List construction</H4>


<P>As of 2.2, you may combine multiple attributes into a single
multi-valued attribute in a syntax similar to the group map feature.
Catenate attributes by placing them in square brackets in a
comma-separated list.  For example,

<div class="code"><PRE>
$[mine,yours]$
</PRE></div>



<P>creates a new multi-valued attribute (a list) with both elements--all
of <TT>mine</TT> first then all of <TT>yours</TT>.  This feature is handy when the
model happens to group attributes differently than you need to access
them in the view.  This ability to rearrange attributes is consistent
with model-view separation because the template cannot alter the data
structure nor test its values--the template is merely looking at the
data from a new perspective.

<P>Naturally you may combine the list construction with template
application:

<div class="code"><PRE>
$[mine,yours]:{ v | ...}$
</PRE></div>



<P>Note that this is very different than

<div class="code"><PRE>
$mine,yours:{ x,y | ...}$
</PRE></div>



<P>which iterates max(n,m) times where n and m are the lengths of <TT>mine</TT>
and <TT>yours</TT>, respectively.  The <TT>[mine,yours]</TT> version iterates n+m
times.
<H4>Attribute operators</H4>


<P>Sometimes you need to treat the first or last element of multi-valued
attribute differently than the others.  For example, if you have a
list of integers in an attribute and you need to generate code to sum
those numbers, you could start like this:

<div class="code"><PRE>
&lt;numbers:{ n | sum += &lt;n&gt;;}&gt;
</PRE></div>



<P>You need to define <TT>sum</TT>, however:

<div class="code"><PRE>
int sum = 0;
&lt;numbers:{ n | sum += &lt;n&gt;;}&gt;
</PRE></div>



<P>What if <TT>numbers</TT> is empty though?  No need to create the <TT>sum</TT>
definition so you could do this:

<div class="code"><PRE>
&lt;if(numbers)&gt;int sum = 0;&lt;endif&gt;
&lt;numbers:{ n | sum += &lt;n&gt;;}&gt;
</PRE></div>



<P>A more specific strategy (and one that generates slightly better code as
it avoids an unnecessary initialization to 0) is the following:

<div class="code"><PRE>
&lt;first(numbers):{ n | int sum += &lt;n&gt;;}&gt;
&lt;rest(numbers):{ n | sum += &lt;n&gt;;}&gt;
</PRE></div>



<P>where <TT>first(numbers)</TT> results in the first value of attribute
<TT>numbers</TT> if any and <TT>rest(numbers)</TT> results all values in <TT>numbers</TT>
but the first value.  

<P>The other operator available to you is <TT>last</TT>, which naturally results
in the last value of a multi-valued attribute.

<P>Special cases:
<UL>
<LI>operations on empty attributes yields an empty value
</LI>
<LI><TT>rest</TT> of a single-valued attribute yields an empty value
</LI>
<LI><TT>tail</TT> of a single-valued attribute yields the same as <TT>first</TT>, the
attribute value
</LI>

</UL>
<H3>Template References</H3>


<P>You may reference other templates to have them included just like the C language preprocessor <TT>#include</TT> construct behaves.  For example, if you are building a web page (<TT>page.st</TT>) that has a search box, you might want the search box stored in a separate template file, say, <TT>searchbox.st</TT>.  This has two advantages:
<OL>
<LI>You can reuse the template over and over (no cut/paste)
</LI>
<LI>You can change one template and all search boxes change on the whole site.
</LI>

</OL>

<P>Using method call syntax, just reference the foreign template:

<div class="code"><PRE>
&lt;html&gt;
&lt;body&gt;
...
$searchbox()$
...
&lt;/body&gt;
&lt;/html&gt;
</PRE></div>



<P>The invoking Java code would still just create the overall page and the enclosing page template would automatically create an instance of the referenced template and insert it:

<div class="code"><PRE>
StringTemplateGroup group =
  new StringTemplateGroup("webpages", "/usr/local/site/templates");
StringTemplate page = group.getInstanceOf("page");
</PRE></div>



<P>If the template you want to reference, say <TT>searchbox</TT>, is in a subdirectory of the <TT>StringTemplateGroup</TT> root directory called <TT>misc</TT>, then you must reference the template as: <TT>misc/searchbox()</TT>.

<P>The included template may access attributes.  How can you set the attribute of an included template?  There are two ways: inheriting attributes and passing parameters.
<H4>Accessing Attributes Of Enclosing Template</H4>


<P>Any included template can reference the attributes of the enclosing template instance.  So if <TT>searchbox</TT> references an attribute called <TT>resource</TT>:

<div class="code"><PRE>
&lt;form ...&gt;
...
&lt;input type=hidden name=resource value=$resource$&gt;
...
&lt;/form&gt;
</PRE></div>



<P>you could set attribute <TT>resource</TT> in the enclosing template <TT>page</TT> object:

<div class="code"><PRE>
StringTemplate page = group.getInstanceOf("page");
page.setAttribute("resource", "faqs");
</PRE></div>



<P>This "inheritance" (<em>dynamic scoping</em> really) of attributes feature is
particularly handy for setting generally useful attributes like
<TT>siteFontTag</TT> in the outermost <TT>body</TT> template and being able to
reference it in any nested template in the body.
<H4>Passing Parameters To Another Template</H4>


<P>Another, more obvious, way to set the attributes of an included template is to pass in values as parameters, making them look like C macro invocations rather than includes.  The syntax looks like a set of attribute assignments:

<div class="code"><PRE>
&lt;html&gt;
&lt;body&gt;
...
$searchbox(resource="faqs")$
...
&lt;/body&gt;
&lt;/html&gt;
</PRE></div>



<P>where I am setting the attribute of the included <TT>searchbox</TT> to be the
string literal <TT>"faqs"</TT>.

<P>The right-hand-side of the assignment may be any expression such as an attribute reference or even a reference to another template like this:

<div class="code"><PRE>
$boldMe(item=copyrightNotice())$
</PRE></div>



<P>You may also use an anonymous template such as:

<div class="code"><PRE>
$bold(it={$firstName$ $lastName$})$
</PRE></div>



<P>which first computes the template argument and then assigns it to
<TT>it</TT>.

<P>If you are using <TT>StringTemplate</TT> groups, then you have formal
parameters and for those templates with a sole formal argument, you
can pass just an expression instead of doing an assignment to the
argument name. For example, if you do <TT>$bold(name)$</TT> and <TT>bold</TT> has
one formal argument call <TT>item</TT>, then <TT>item</TT> gets the value of <TT>name</TT>
just as if you had said <TT>$bold(item=name)$</TT>.
<H5>Allowing enclosing attributes to pass through</H5>


<P>When template <TT>x</TT> calls template <TT>y</TT>, the formal arguments of <TT>y</TT> hide
any <TT>x</TT> arguments of the same because the formal parameters force you
to define values.  This prevents surprises and makes it easy to ensure
any parameter value is empty unless you specifically set it for that
template.  The problem is that you need to factor templates sometimes
and want to refine behavior with a subclass or just invoke another
shared template but invoking <TT>y</TT> as <TT>&lt;y()&gt;</TT> hides all of <TT>x</TT>'s
parameters with the same name.  Use <TT>&lt;y(...)&gt;</TT> syntax to indicate y
should inherit all values even those with the same name.
<TT>&lt;y(name="foo", ...)&gt;</TT> would set one arg, but the others are inherited
whereas <TT>&lt;y(name="foo")&gt;</TT> only has <TT>name</TT> set; all other arguments of
template <TT>y</TT> are empty. You can set manually with
<TT>StringTemplate.setPassThroughAttributes()</TT>.
<H5>Argument evaluation scope</H5>


<P>The right-hand-side of the argument assignments are evaluated
within the scope of the enclosing template whereas the left-hand-side
attribute name is the name of an attribute in the target template.
Template invocations like <TT>$bold(item=item)$</TT> actually make sense
because the <TT>item</TT> on the right is evaluated in a different scope.
<H3>Attribute Expressions</H3>


<P>When setting parameters or testing IF conditionals, you may find it handy to use the plus "string concatenate" operator.  For example, when building web pages, you will find it useful to create a template called <TT>link</TT> and then use it to generate HTML link tags; you may want to change the way every link looks on your site and it's convenient to have one place to change things.  The template might look like:

<div class="code"><PRE>
&lt;a href="$url$"&gt;&lt;b&gt;$title$&lt;/b&gt;&lt;/a&gt;
</PRE></div>



<P>Then in a page template you might reference:

<div class="code"><PRE>
...$link(url="http://www.jguru.com", title="jGuru")$...
</PRE></div>



<P>or you could use attributes to set the link parameters:

<div class="code"><PRE>
...$link(url=person.homePage, title=person.name)$...
</PRE></div>



<P>Sometimes you may want to compute the URL; usually it is enough to concatenate strings:

<div class="code"><PRE>
...$link(url="/faq/view?ID="+faqid, title=faqtitle)$...
</PRE></div>



<P>where <TT>faqid</TT> and <TT>faqtitle</TT> are attributes you would have to set for
the template that referenced <TT>link</TT>.

<P>Terence says: <em>I'm a little uncomfortable with this catenation
operation.  Please use a template instead</em>:

<div class="code"><PRE>
...$link(url={/faq/view?ID=$faqid$}, title=faqtitle)$...
</PRE></div>


<H3>Template Application</H3>


<P>Imagine a simple template called <TT>bold</TT>:

<div class="code"><PRE>
&lt;b&gt;$item$&lt;/b&gt;
</PRE></div>



<P>Just as with template <TT>link</TT> described above, you can reference it from a template by invoking it like a method call:

<div class="code"><PRE>
$bold(item=name)$
</PRE></div>



<P>What if you want something bold and italicized?  You could simply nest the template reference:

<div class="code"><PRE>
$bold(item=italics(item=name))$
</PRE></div>



<P>where template <TT>italics</TT> is defined as:

<div class="code"><PRE>
&lt;i&gt;$item$&lt;/i&gt;
</PRE></div>



<P>using a different attribute with the same name, <TT>item</TT>; the attributes have different values just like you would expect if these template references where Java method calls and <TT>item</TT> were a local variable.  Parameters and attribute references are scoped like a programming language.

<P>Think about what you are really trying to say here.  You want to say "make name italics and then make it bold", or "apply italics to the name and then apply bold."  There is an "apply template" syntax that is a literal translation:

<div class="code"><PRE>
$name:italics():bold()$
</PRE></div>



<P>where the templates are applied in the order specified from left to right.  This is much more clear, particularly if you had three templates to apply:

<div class="code"><PRE>
$name:courierFont():italics():bold()$
</PRE></div>



<P>For this syntax to work, however, the applied templates have to reference a standard attribute because you are not setting the attribute in a parameter assignment.  In general for syntax <em>expr</em>:<em>template</em>(), an attribute called <TT>it</TT> is set to the value of <em>expr</em>.  So, the definition of <TT>bold</TT> (and analogously <TT>italics</TT>), would have to be:

<div class="code"><PRE>
&lt;b&gt;$it$&lt;/b&gt;
</PRE></div>



<P>to pick up the value of <TT>name</TT> in our examples above.

<P>As of 2.2 <TT>StringTemplate</TT>, you can avoid using <TT>it</TT> as a default
parameter by using formal arguments.  For expression <TT>$x:y()$</TT>,
<TT>StringTemplate</TT> will assign the value of <TT>x</TT> to <TT>it</TT> and any sole
formal argument of <TT>y</TT>.  For example, if <TT>y</TT> is:

<div class="code"><PRE>
y(item) ::= "_$item$_"
</PRE></div>



<P>then <TT>item</TT> would also have the value of <TT>x</TT>.
<H4>Applying Templates To Multi-Valued Attributes</H4>


<P>Where template application really shines though is when an attribute is multi-valued.  One of the most common web page generation issues is making lists of items either as bullet lists or table rows etc...  Applying a template to a multi-valued attribute means that you want the template applied to each of the values.

<P>Consider a list of names (i.e., you set attribute <TT>names</TT> multiple times) that you want in a bullet list.  If you have a template called <TT>listItem</TT>:

<div class="code"><PRE>
&lt;li&gt;$it$&lt;/li&gt;
</PRE></div>



<P>then you can do this:

<div class="code"><PRE>
&lt;ul&gt;
$names:listItem()$
&lt;/ul&gt;
</PRE></div>



<P>and each name will appear as a bullet item. For example, if you set <TT>names</TT> to <TT>"Terence"</TT>, <TT>"Tom"</TT>, and <TT>"Jim"</TT>, then you would see:

<div class="code"><PRE>
&lt;ul&gt;
&lt;li&gt;Terence&lt;/li&gt;
&lt;li&gt;Tom&lt;/li&gt;
&lt;li&gt;Jim&lt;/li&gt;
&lt;/ul&gt;
</PRE></div>



<P>in the output.

<P>Whenever you apply a template to an attribute or multi-valued attribute, the default attribute <TT>it</TT> is set.  Another attribute <TT>i</TT> (of type <TT>Integer</TT>) is also set to the value's index number starting from 1.  For example, if you wanted to make your own style of numbered list, you could reference <TT>i</TT> to get the index:

<div class="code"><PRE>
$names:numberedListItem()$
</PRE></div>



<P>where template <TT>numberedListItem</TT> is defined as:

<div class="code"><PRE>
$i$. $it$&lt;br&gt;
</PRE></div>



<P>In this case, the output would be:

<div class="code"><PRE>
1. Terence&lt;br&gt;
2. Tom&lt;br&gt;
3. Jim&lt;br&gt;
</PRE></div>



<P>If there is only one attribute value, then <TT>i</TT> will be 1.

<P>As when invoking templates ala "includes", a single formal argument is
also set to the iterated value.  For example, you could define
<TT>numberedListItem</TT> as follows in a <TT>StringTemplateGroup</TT> file:

<div class="code"><PRE>
numberedListItem(item) ::= "$i$. $item$&lt;br&gt;"
</PRE></div>


<H4>Applying Multiple Templates To Multi-Valued Attributes</H4>


<P>The result of applying a template to a multi-valued attribute is another multi-valued attribute containing the results of the application.  You may apply another template to the results of the first template application, which comes in handy when you need to format the elements of a list before they go into the list.  For example, to bold the elements of a list do the following (given the appropriate template definitions from above):

<div class="code"><PRE>
$names:bold():listItem()$
</PRE></div>

 

<P>If you actually want to apply a template to the combined (string) result of a previous template application, enclose the previous application in parenthesis.  The parenthesis will force immediate evaluation of the template application, resulting in a string.  For example,

<div class="code"><PRE>
$(names:bold()):listItem()$
</PRE></div>

 

<P>results in a single list item full of a bunch of bolded names.  Without the parenthesis, you get a list of items that are bolded.
<H4>Applying Alternating Templates To Multi-Valued Attributes</H4>


<P>When generating lists of things, you often need to change the color or other formatting instructions depending on the list position.  For example, you might want to alternate the color of the background for the elements of a list.  The easiest and most natural way to specify this is with an alternating list of templates to apply to an expression of the form: <TT>$</TT><em>expr</em>:<em>t1</em>(),<em>t2</em>(),...,<em>tN</em>()<TT>$</TT>.  To make an alternating list of blue and green names, you might say:

<div class="code"><PRE>
$names:blueListItem(),greenListItem()$
</PRE></div>



<P>where presumably <TT>blueListItem</TT> template is an HTML <TT>&lt;table&gt;</TT> or something that lets you change background color.   <TT>names[0]</TT> would get <TT>blueListItem()</TT> applied to it, <TT>names[1]</TT> would get <TT>greenListItem()</TT>, and <TT>names[2]</TT> would get <TT>blueListItem()</TT>, etc...

<P>If <TT>names</TT> is single-valued, then <TT>blueListItem()</TT> is applied and that's it.
<H4>Applying Anonymous Templates</H4>


<P>Some templates are so simple or so unlikely to be reused that it seems a waste of time making a separate template file and then referencing it.  <TT>StringTemplate</TT> provides <em>anonymous subtemplates</em> to handle this case.  The templates are anonymous in the sense that they are not named; they are directly applied in a single instance.

<P>For example, to show a name list do the following:

<div class="code"><PRE>
&lt;ul&gt;
$names:{&lt;li&gt;$it$&lt;/li&gt;}$
&lt;/ul&gt;
</PRE></div>



<P>where anything enclosed in curlies is an anonymous subtemplate if, of course, it's within an attribute expression.  Note that in the subtemplate, I must enclose the <TT>it</TT> reference in the template expression delimiters.  You have started a new template exactly like the surrounding template and you must distinguish between text and attribute expressions.

<P>You can apply multiple templates very conveniently.  Here is the bold list of names again with anonymous templates:

<div class="code"><PRE>
&lt;ul&gt;
$names:{&lt;b&gt;$it$&lt;/b&gt;}:{&lt;li&gt;$it$&lt;/li&gt;}$
&lt;/ul&gt;
</PRE></div>



<P>The output would look like:

<div class="code"><PRE>
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Terence&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Tom&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Jim&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
</PRE></div>



<P>Anonymous templates work on single-valued attributes as well.

<P>As of 2.2, you may define formal arguments on anonymous templates even
if you are not using <TT>StringTemplate</TT> groups.  I have borrowed the
syntax from SmallTalk though it is identical in function to <TT>lamba</TT> of
Python.  Use a comma-separated list of argument names followed by the
'<TT>|</TT>' "pipe" symbol.  Any single whitespace character immediately
following the pipe is ignored.  The following example bolds the names
in a list using an argument to avoid the monotonous use of <TT>it</TT>:

<div class="code"><PRE>
&lt;ul&gt;
$names:{ n | &lt;b&gt;$n$&lt;/b&gt;}$
&lt;/ul&gt;
</PRE></div>



<P>Clearly only one argument may be defined in this situation: the
iterated value of a single list.
<H4>Anonymous template application to multiple attributes</H4>


<P>In some cases, the model may present data to the view as separate
columns of data rather than as a single list of objects, such as
multi-valued attributes <TT>names</TT> and <TT>phones</TT> rather than a single
<TT>users</TT> multi-valued attribute.  As of 2.2, you may iterate over
multiple attributes:

<div class="code"><PRE>
$names,phones:{ n,p | $n$: $p$}$
</PRE></div>



<P>An error is generated if you have too many arguments for the number of
attributes.  Iteration proceeds while at least one of the attributes
(<TT>names</TT> or <TT>phones</TT>, in this case) has values.
<H4>Indirect template references</H4>


<P>Sometimes the name of the template you would like to include is itself
a variable.  So, rather than using "<TT>&lt;item:format()&gt;</TT>" you want the
name of the template, <TT>format</TT>, to be a variable rather than a
literal.  Just enclose the template name in parenthesis to indicate
you want the immediate value of that attribute and then add <TT>()</TT> like
a normal template invocation and you get "<TT>&lt;item:(someFormat)()&gt;</TT>",
which means "look up attribute <TT>someFormat</TT> and use its value as a
template name; appy to <TT>item</TT>."  This deliberately looks similar to
the C function call indirection through a function pointer (e.g.,
"<TT>(*fp)()</TT>" where fp is a pointer to a function).  A better way to look at
it though is that the <TT>(someFormat)</TT> implies <em>immediately evaluate someFormat and use as the template name</em>.

<P>Usually this "variable template" situation occurs when you have a list
of items to format and each element may require a different template.
Rather than have the controller code create a bunch of instances, one
could consider it better to have <TT>StringTemplate</TT> do the creation--the
controller just names what format to use.

<P>If <TT>StringTemplate</TT> did not have a map definition, you could simulate
its functionality.  Consider generating a list of Java declarations
that are initialized to 0, false, null, etc...  You could define a
template for <TT>int</TT>, <TT>Object</TT>, <TT>Array</TT>, etc... declarations and then
pass in an aggregate object that has the variable declaration object
and the format.  In a template group file you might have:

<div class="code"><PRE>
group Java;

file(variables,methods) ::= &lt;&lt;
&lt;variables:{ v | &lt;v.decl:(v.format)()&gt;}; separator="\n"&gt;
&lt;methods&gt;
&gt;&gt;
intdecl(decl) ::= "int &lt;decl.name&gt; = 0;"
intarray(decl) ::= "int[] &lt;decl.name&gt; = null;"
</PRE></div>



<P>Your code might look like:

<div class="code"><PRE>
StringTemplateGroup group =
        new StringTemplateGroup(new StringReader(templates),
                AngleBracketTemplateLexer.class);
StringTemplate f = group.getInstanceOf("file");
f.setAttribute("variables.{decl,format}", new Decl("i","int"), "intdecl");
f.setAttribute("variables.{decl,format}", new Decl("a","int-array"), "intarray");
System.out.println("f="+f);
String expecting = ""+newline+newline;
</PRE></div>



<P>For this simple unit test, I used the following dummy decl class:

<div class="code"><PRE>
public static class Decl {
    String name;
    String type;
    public Decl(String name, String type) {this.name=name; this.type=type;}
    public String getName() {return name;}
    public String getType() {return type;}
}
</PRE></div>



<P>The value of <TT>f.toString()</TT> is:

<div class="code"><PRE>
int i = 0;
int[] a = null;
</PRE></div>



<P>Missing attributes (i.e., <TT>null</TT> valued attributes) used as indirect
template attribute generate nothing just like referencing a missing
attribute.
<H3>Conditionally Included Subtemplates (IF statements)</H3>


<P>There are many situations when you want to conditionally include some text or another template.  <TT>StringTemplate</TT> provides simple IF-statements to let you specify conditional includes.  For example, in a dynamic web page you usually want a slightly different look depending on whether or not the viewer is "logged in" or not.  Without a conditional include, you would need two templates: <TT>page_logged_in</TT> and <TT>page_logged_out</TT>.  You can use a single <TT>page</TT> definition with <TT>if(</TT><em>expr</em><TT>)</TT> attribute actions instead:

<div class="code"><PRE>
&lt;html&gt;
...
&lt;body&gt;
$if(member)$
$gutter/top_gutter_logged_in()$
$else$
$gutter/top_gutter_logged_out()$
$endif$
...
&lt;/body&gt;
&lt;/html&gt;
</PRE></div>

 

<P>where template <TT>top_gutter_logged_in</TT> is located in the <TT>gutter</TT> subdirectory of my <TT>StringTemplateGroup</TT>.

<P>IF actions test the presence or absence of an attribute unless the
object is a <TT>Boolean</TT>, in which case it tests the attribute for
<TT>true</TT>/<TT>false</TT>.  The only operator allowed is "not" and means either
"not present" or "not true".  For example,
"<TT>$if(!member)$...$endif$</TT>".
<H4>Whitespace in conditionals issue</H4>


<P>There is a simple, but not perfect rule: kill a single newline <B>after</B>
<TT>&lt;if&gt;</TT>, <TT>&lt;&lt;</TT>, <TT>&lt;else&gt;</TT>, and <TT>&lt;endif&gt;</TT> (but for <TT>&lt;endif&gt;</TT> only if it's
on a line by itself) . Kill newlines <B>before</B> <TT>&lt;else&gt;</TT> and <TT>&lt;endif&gt;</TT>
and <TT>&gt;&gt;</TT>.  For example,

<div class="code"><PRE>
a &lt;if(foo)&gt;big&lt;else&gt;small&lt;endif&gt; dog
</PRE></div>



<P>is identical to:

<div class="code"><PRE>
a &lt;if(foo)&gt;
big
&lt;else&gt;
small
&lt;endif&gt;
 dog
</PRE></div>



<P>It is very difficult to get the newline rule to work "properly"
because sometimes you want newlines and sometimes you don't.  I
decided to chew up as many as is reasonable and then let you
explicitly say <TT>&lt;\n&gt;</TT> when you need to.
<H3>Template visualization</H3>


<P>Sometimes you use or define templates improperly.  Either you set an
attribute that is not used or forget to set one or reference the wrong
template etc...  I have made a toy visualization tool via that shows
both the attributes and the way <TT>StringTemplate</TT> breaks up your
template into chunks.  It properly handles <TT>StringTemplate</TT> objects as
attributes and other nested structures.  Here is the way to launch a
Swing frame to view your template:

<div class="code"><PRE>
StringTemplate st = ...;
StringTemplateTreeView viz =
    new StringTemplateTreeView("sample",st);
viz.setVisible(true);
</PRE></div>



<P>Here is a snapshot (note that due some weird font thing on my os x
box, the first <TT>&lt;html&gt;</TT> text chunk is missing in the display.) :( The
display is associated with the fill-a-table example below.

<P> <img src="page.treeview.jpg"  > 

<P>If you turn on "lint mode" via <TT>StringTemplate.setLintMode(true)</TT> then
you may access attribute <TT>attributes</TT>, which is a text string that
recursively dumps out types, properties, etc... It does not print out
their values.
<H2>Functionality Summary</H2>


<TABLE cellspacing=0 border=1>
<TR><TD>
<B>Syntax</B> </TD><TD> <B>Description</B>
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>&gt;
</TD><TD> Evaluates to the value of <em>attribute</em><TT>.toString()</TT> if it exists else empty string.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>.<em>property</em>&gt;
</TD><TD> Looks for <em>property</em> of <em>attribute</em> via JavaBeans accessor methods
like <TT>get</TT><em>Property</em><TT>()</TT> or <TT>is</TT><em>Property</em><TT>()</TT>.  If that fails,
<TT>StringTemplate</TT> looks for a raw field of the <em>attribute</em> called <em>property</em>.
Evaluates to the empty string if no such property is found.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>.(<em>expr</em>)&gt;
</TD><TD> Indirect property lookup.  Same as <em>attribute</em>.<em>property</em> except
use the value of <em>expr</em> as the <em>property</em> name.
Evaluates to the empty string if no such property is found.
</TD>
</TR>
<TR>
<TD>
&lt;<em>multi-valued-attribute</em>&gt;
</TD><TD> Concatenation of <TT>toString()</TT> invoked on each element.  If <em>multi-valued-attribute</em> is missing this evaluates to the empty string.
</TD>
</TR>
<TR>
<TD>
&lt;<em>multi-valued-attribute</em>; separator=<em>expr</em>&gt;
</TD><TD> Concatenation of <TT>toString()</TT> invoked on each element separated by <em>expr</em>. 
</TD>
</TR>
<TR>
<TD>
&lt;<em>template</em>(<em>argument-list</em>)&gt;
</TD><TD> Include <em>template</em>.  The <em>argument-list</em> is a list of attribute
assignments where each assignment is of the form <em>arg-of-template</em>=<em>expr</em>
where <em>expr</em> is evaluated in the context of the surrounding template
not of the invoked template.
</TD>
</TR>
<TR>
<TD>
&lt;<em>(expr)</em>(<em>argument-list</em>)&gt;
</TD><TD> Include <em>template</em> whose name is computed via <em>expr</em>.  The <em>argument-list</em> is a list of attribute assignments where each assignment is of the form <em>attribute</em>=<em>expr</em>.  Example <TT>$(whichFormat)()$</TT> looks up <TT>whichFormat</TT>'s value and uses that as template name.  Can also apply an indirect template to an attribute.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:<em>template</em>(<em>argument-list</em>)&gt;
</TD><TD> Apply <em>template</em> to <em>attribute</em>.  The optional <em>argument-list</em> is
evaluated before application so that you can set attributes referenced
within <em>template</em>.  The default attribute <TT>it</TT> is set to the value of
<em>attribute</em>.  If <em>attribute</em> is multi-valued, then <TT>it</TT> is set to each
element in turn and <em>template</em> is invoked <em>n</em> times where <em>n</em> is the
number of values in <em>attribute</em>.  Example: <TT>$name:bold()</TT> applies
<TT>bold()</TT> to <TT>name</TT>'s value.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:<em>(expr)</em>(<em>argument-list</em>)&gt;
</TD><TD> Apply a template, whose name is computed from <em>expr</em>, to
each value of <em>attribute</em>.  Example <TT>$data:(name)()$</TT> looks up
<TT>name</TT>'s value and uses that as template name to apply to <TT>data</TT>. 
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:<em>t1</em>(<em>argument-list</em>): ... :<em>tN</em>(<em>argument-list</em>)&gt;
</TD><TD> Apply multiple templates in order from left to right.
The result of a template application upon a multi-valued attribute is
another multi-valued attribute.  The overall expression evaluates to
the concatenation of all elements of the final multi-valued attribute
resulting from <em>templateN</em>'s application.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:{<em>anonymous-template</em>}&gt;
</TD><TD> Apply an anonymous template to each element of <em>attribute</em>.  The
iterated <TT>it</TT> attribute is set automatically.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:{<em>argument-name</em> | <em>anonymous-template</em>}&gt;
</TD><TD> Apply an anonymous template to each element of <em>attribute</em>.  Set the
<em>argument-name</em> to the iterated value and also set <TT>it</TT>.
</TD>
</TR>
<TR>
<TD>
&lt;<em>a1</em>,<em>a2</em>,...,<em>aN</em>:{<em>argument-list</em> | <em>anonymous-template</em>}&gt;
</TD><TD> Parallel list iteration.  March through the values of the attributes
<em>a1</em>..<em>aN</em>, setting the values to the arguments in <em>argument-list</em> in
the same order.  Apply the anonymous template.  There is no defined
<TT>it</TT> value unless inherited from an enclosing scope.
</TD>
</TR>
<TR>
<TD>
&lt;<em>attribute</em>:<em>t1</em>(),<em>t2</em>(),...,<em>tN</em>()&gt;
</TD><TD> Apply an alternating list of templates to the elements of
<em>attribute</em>.  The template names may include argument lists.
</TD>
</TR>
<TR>
<TD>
&lt;if(<em>attribute</em>)&gt;<em>subtemplate</em>
&lt;else&gt;<em>subtemplate2</em>
&lt;endif&gt;
</TD><TD> If <em>attribute</em> has a value or is a <TT>true</TT> <TT>Boolean</TT> object, include <em>subtemplate</em> else include <em>subtemplate2</em>.  These conditionals may be nested.
</TD>
</TR>
<TR>
<TD>
&lt;if(!<em>attribute</em>)&gt;<em>subtemplate</em>&lt;endif&gt;
</TD><TD> If <em>attribute</em> has no value or is a <TT>false</TT> <TT>Boolean</TT> object, include <em>subtemplate</em>.  These conditionals may be nested.
</TD>
</TR>
<TR>
<TD>
<TT>\$</TT> or <TT>\&lt;</TT> </TD><TD> escaped delimiter prevents <TT>$</TT> or <TT>&lt;</TT> from starting an attribute
expression and results in that single character.
</TD>
</TR>
<TR>
<TD>
<TT>&lt;\ &gt;</TT>, <TT>&lt;\n&gt;</TT>, <TT>&lt;\t&gt;</TT>, <TT>&lt;\r&gt;</TT> </TD><TD> special characters: space, newline,
tab, carriage return.
</TD>
</TR>
<TR>
<TD>
<TT>&lt;! comment !&gt;</TT>, <TT>$! comment !$</TT> </TD><TD> Comments, ignored by StringTemplate.
</TD></TR>
</TABLE>

<H2>Object Rendering</H2>


<P>The atomic element of a template is a simple object that is rendered
to text by its <TT>toString()</TT> method (in Java).  For example, an
<TT>Integer</TT> object is converted to text as a sequence of characters
representing the numeric value written out.  What if you wanted commas
to separate the 1000's places like <TT>1,000,000</TT>?  What if you wanted
commas and sometimes periods depending on the locale?  Prior to 2.2,
there was no means of altering the rendering of objects to text.  The
controller had to pull data from the model and wrap it on an object
whose <TT>toString()</TT> method rendered it appropriately.

<P>As of <TT>StringTemplate</TT> 2.2, you may register various attribute
renderers associated with object class types.  Normally a single
renderer will be used for a group of templates so that <TT>Date</TT> objects
are always displayed using the appropriate <TT>Locale</TT>, for example.
There are, however, situations where you might want a template to
override the group renderers.  You may register renderers with either
templates or groups and groups inherit the renderers from super groups
(if any).

<P>There is a new interface, <TT>AttributeRenderer</TT>, that defines how an
object is rendered to string.  Here is a renderer that renders
<TT>Calendar</TT> date objects tersely.

<div class="code"><PRE>
public class DateRenderer implements AttributeRenderer {
	public String toString(Object o) {
		SimpleDateFormat f = new SimpleDateFormat("yyyy.MM.dd");
		return f.format(((Calendar)o).getTime());
	}
}
...
StringTemplate st =new StringTemplate(
		"date: &lt;created&gt;",
		AngleBracketTemplateLexer.class);
st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05));
st.registerRenderer(GregorianCalendar.class, new DateRenderer());
String expecting = "date: 2005.07.05";
String result = st.toString();
</PRE></div>



<P>All attributes of type <TT>GregorianCalendar</TT> in template <TT>st</TT> are
rendered using the <TT>DateRenderer</TT> object.

<P>You will notice that there is no way for the template to say which
renderer to use.  Allowing such a mechanism would effectively imply an
ability to call random code from the template.  In <TT>StringTemplate</TT>'s
scheme, only the model or controller can set the renderer.  The
template must still reference a simple attribute such as <TT>&lt;created&gt;</TT>.
If you need the same kind of attribute displayed differently within
the same template or group, you must pass in two different attribute
types.  This would be rare, but if you need it, you can easily still
wrap an object in a renderer before sending it to the template as an
attribute. For example, if you have a web site that allows editing of
some descriptions, you will probably need both an escaped and
unescaped version of the description.  Send in the unescaped
description as one attribute and send it in again wrapped in an HTML
escape renderer as a different attribute.

<P>As far as I can tell, this functionality is mostly useful in the web
page generation realm rather than code generation; perhaps an
opportunity will present it self though.
<H2>Template Inheritance</H2>


<P>Recall that a StringTemplateGroup is a collection of related templates
such as all templates associated with the look of a web site. If you
want to design a similar look for that site (such as for premium
users), you don't really want to cut-n-paste the original template
files for use in the new look. Changes to the original will not be
propogated to the new look.

<P>Just like you would do with a class definition, a template group may
inherit templates from another group, the <em>supergroup</em>.  If template
<em>t</em> is not found in a group, it is looked up in the supergroup, if
present.  This works regardless of whether you use a group file format
or load templates from the disk via a <TT>StringTemplateGroup</TT> object.
Currently you cannot use the group file syntax to specify a
supergroup.  I am investigating how this should work.  In the
meantime, you must explicitly set the super.

<P>From my unit tests, here is a simple inheritance of a template, <TT>bold</TT>:

<div class="code"><PRE>
StringTemplateGroup supergroup = new StringTemplateGroup("super");
StringTemplateGroup subgroup = new StringTemplateGroup("sub");
supergroup.defineTemplate("bold", "&lt;b&gt;$it$&lt;/b&gt;");
subgroup.setSuperGroup(supergroup);
StringTemplate st = new StringTemplate(subgroup, "$name:bold()$");
st.setAttribute("name", "Terence");
String expecting = "&lt;b&gt;Terence&lt;/b&gt;";
</PRE></div>



<P>The supergroup has a bold definition but the subgroup does not.  Referencing <TT>$name:bold()$</TT> works because subgroup looks into its supergroup if it is not found.

<P>You may override templates:

<div class="code"><PRE>
supergroup.defineTemplate("bold", "&lt;b&gt;$it$&lt;/b&gt;");
subgroup.defineTemplate("bold", "&lt;strong&gt;$it$&lt;/strong&gt;");
</PRE></div>



<P>And you may refer to a template in a supergroup via <TT>super.</TT><em>template</em><TT>()</TT>:

<div class="code"><PRE>
StringTemplateGroup group = new StringTemplateGroup(...);
StringTemplateGroup subGroup = new StringTemplateGroup(...);
subGroup.setSuperGroup(group);
group.defineTemplate("page", "$font()$:text");
group.defineTemplate("font", "Helvetica");
subGroup.defineTemplate("font", "$super.font()$ and Times");
StringTemplate st = subGroup.getInstanceOf("page");
</PRE></div>



<P>The string <TT>st.toString()</TT> results in "<TT>Helvetica and Times:text</TT>".

<P>Just like object-oriented programming languages, <TT>StringTemplate</TT> has polymorphism.  That is, template names are looked up dynamically relative to the invoking templates group.  The classic demonstration of dynamic message sends in Java, for example, would be the following example that catches my students all the time: ;)

<div class="code"><PRE>
class A {
  public void page() {bold();}
  public void bold() {System.out.println("A.bold");}
}
class B extends A {
  public void bold() {System.out.println("B.bold");}
}
...
A a = new B();
a.page();
</PRE></div>



<P>This prints "<TT>B.bold</TT>" not "<TT>A.bold</TT>" because the receiver determines how to answer a message not the type of the variable.  So, I have created a <TT>B</TT> object meaning that any message, such as <TT>bold()</TT>, invoked will first look in class <TT>B</TT> for <TT>bold()</TT>.

<P>Similarly, a template's group determines where it starts looking for a template.  In this case, both super and sub groups define a <TT>bold</TT> template mirroring the Java above.  Because I create template <TT>st</TT> as a member of the <TT>subGroup</TT> and reference to <TT>bold</TT> starts looking in <TT>subGroup</TT> even though <TT>page</TT> is the template referring to <TT>bold</TT>.

<div class="code"><PRE>
StringTemplateGroup group = new StringTemplateGroup("super");
StringTemplateGroup subGroup = new StringTemplateGroup("sub");
subGroup.setSuperGroup(group);
group.defineTemplate("bold", "&lt;b&gt;$it$&lt;/b&gt;");
group.defineTemplate("page", "$name:bold()$");
subGroup.defineTemplate("bold", "&lt;strong&gt;$it$&lt;/strong&gt;");
StringTemplate st = subGroup.getInstanceOf("page");
st.setAttribute("name", "Ter");
String expecting = "&lt;strong&gt;Ter&lt;/strong&gt;";
</PRE></div>



<P><TT>StringTemplate</TT> group maps also inherit.  If an attribute reference
is not found, <TT>StringTemplate</TT> looks for a map in its group with that
name.  If not found, the super group is checked.
<H2>Template And Attribute Lookup Rules</H2>

<H3>Template lookup</H3>


<P>When you request a named template via <TT>StringTemplateGroup.getInstanceOf()</TT> or within a template, there is a specific sequence used to locate the template.

<P>If a template, <em>t</em>, references another template and <em>t</em> is not specifically associated with any group, <em>t</em> is implicitly associated with a default group whose root directory is "<TT>.</TT>", the current directory.  The referenced template will be looked up in the current directory.

<P>If a template <em>t</em> is associated with a group, but was not defined via a group file format, lookup a referenced template in the group's template table.  If not there, look for it on the disk under the group's root dir or via the <TT>CLASSPATH</TT> (it might have appeared dynamically on disk).  If not found, recursively look at any supergroup of the group.  If not found at all, record this fact and don't look again on the disk until refresh interval.

<P>If the template's associated group was defined via a group file, then that group is searched first.  If not found, the template is looked up in any supergroup.  The refresh interval is not used for group files because the group file is considered complete and enduring.
<H3>Attribute scoping rules</H3>


<P>A <TT>StringTemplate</TT> is a list of chunks, text literals and attribute expressions, and an attributes table.  To render a template to string, the chunks are written out in order; the expressions are evaluated only when asked to during rendering.  Attributes referenced in expressions are looked up using a very specific sequence similar to an inheritance mechanism.

<P>When you nest a template within another, such as when a <TT>page</TT> template references a <TT>searchbox</TT> template, the nested template may see any attributes of the enclosing instance or its enclosing instances.  This mechanism is called <em>dynamic scoping</em>.  Contrast this with <em>lexical scoping</em> used in most programming languages like Java where a method may not see the variables defined in invoking methods.  Dynamic scoping is very natural for templates.  For example, if <TT>page</TT> has an attribute/value pair <TT>font</TT>/<TT>Times</TT> then <TT>searchbox</TT> could reference <TT>$font$</TT> when nested within a <TT>page</TT> instance.

<P>Reference to attribute <em>a</em> in template <em>t</em> is resolved as follows:
<OL>
<LI>Look in <em>t</em>'s attribute table
</LI>
<LI>Look in <em>t</em>'s arguments
</LI>
<LI>Look recursively up <em>t</em>'s enclosing template instance chain
</LI>
<LI>Look recursively up <em>t</em>'s group / supergroup chain for a map
</LI>

</OL>

<P>This process is recursively executed until <em>a</em> is found or there are
no more enclosing template instances or super groups.

<P>When using a group file format to specify templates, you must specify
the formal arguments for that template.  If you try to access an
attribute that is not formally defined in that template or an
enclosing template, you will get a <TT>NoSuchElementException</TT>.

<P>When building code generators with <TT>StringTemplate</TT>, large heavily
nested template tree structures are commonplace and, due to dynamic
attribute scoping, a nested template could inadvertently use an
attribute from an enclosing scope.  This could lead to infinite
recursion during rendering and other surprises.  To prevent this,
formal arguments on template <em>t</em> hide any attribute value with that
name in any enclosing scope.  Here is a test case that illustrates the
point.

<div class="code"><PRE>
String templates =
        "group test;" +newline+
        "block(stats) ::= \"{$stats$}\""
        ;
StringTemplateGroup group =
        new StringTemplateGroup(new StringReader(templates));
StringTemplate b = group.getInstanceOf("block");
b.setAttribute("stats", group.getInstanceOf("block"));
String expecting ="{{}}";
</PRE></div>



<P>Even though <TT>block</TT> has a <TT>stats</TT> value that refers to itself, there
is no recursion because each instance of <TT>block</TT> hides the <TT>stats</TT>
value from above since <TT>stats</TT> is a formal argument.

<P>Sometimes self-recursive (hence infinitely recursive) structures occur
through programming error and they are nasty to track down.  If you
turn on "lint mode", <TT>StringTemplate</TT> will attempt to find cases where
a template instance is being evaluated during the evaluation of
itself.  For example, here is a test case that causes and traps
infinite recursion.

<div class="code"><PRE>
String templates =
        "group test;" +newline+
        "block(stats) ::= \"$stats$\"" +
        "ifstat(stats) ::= \"IF true then $stats$\"\n"
        ;
StringTemplate.setLintMode(true);
StringTemplateGroup group =
        new StringTemplateGroup(new StringReader(templates));
StringTemplate b = group.getInstanceOf("block");
StringTemplate ifstat = group.getInstanceOf("ifstat");
b.setAttribute("stats", ifstat); // block has if stat
ifstat.setAttribute("stats", b); // but make the "if" contain block
try {
    String result = b.toString();
}
catch (IllegalStateException ise) {
    ...
}
</PRE></div>



<P>The nested template stack trace from <TT>ise.getMessage()</TT> will be similar to:

<div class="code"><PRE>
infinite recursion to &lt;ifstat([stats])@4&gt; referenced in &lt;block([stats])@3&gt;; stack trace:
&lt;ifstat([stats])@4&gt;, attributes=[stats=&lt;block()@3&gt;]&gt;
&lt;block([stats])@3&gt;, attributes=[stats=&lt;ifstat()@4&gt;], references=[stats]&gt;
&lt;ifstat([stats])@4&gt; (start of recursive cycle)
...
</PRE></div>


<H2>Setting the Expression Delimiters</H2>


<P>By default, expressions in a template are delimited by dollar signs:
<TT>$...$</TT>.  This works great for the most common case of HTML generation
because the attribute expressions are clearly highlighted in the text.
Sometimes, with other formats like SQL statement generation, you may
want to change the template expression delimiters to avoid a conflict
and to make the expressions stand out.

<P>As of 2.0, the start and stop strings are limited to either <TT>$...$</TT> or <TT>&lt;...&gt;</TT> (unless you build your own lexical analyzer to break apart templates into chunks).

<P>To use the angle bracket delimiters you must create a <TT>StringTemplateGroup</TT>:

<div class="code"><PRE>
StringTemplateGroup group =
  new StringTemplateGroup("sqlstuff", "/tmp", AngleBracketTemplateLexer.class);
StringTemplate query =
  new StringTemplate(group, "SELECT &lt;column&gt; FROM &lt;table&gt;;");
query.setAttribute("column", "name");
query.setAttribute("table", "User");
</PRE></div>



<P>All templates created through the group or in anyway associated with
the group will assume your the angle bracket delimiters.  It's smart to be
consistent across all files of similar type such as "all HTML
templates use <TT>$...$</TT>" and "all SQL templates use <TT>&lt;...&gt;</TT>".
<H2>Caching</H2>


<P>By default templates are loaded from disk just once.  During
development, however, it is convenient to turn caching off.  Also, you
may want to turn off caching so that you can quickly update a running
site.  You can set a simple refresh interval using
<TT>StringTemplateGroup.setRefreshInterval(...)</TT>.  When the interval is
reached, all templates are thrown out.  Set interval to 0 to refresh
constantly (no caching).  Set the interval to a huge number like
<TT>Integer.MAX_INT</TT> to have no refreshing at all.

<P>
<H2>Output Filters</H2>


<P>2.0 introduced the notion of a <TT>StringTemplateWriter</TT>.  All text
rendered from a template goes through one of these writers before
being placed in the output buffer.  I added this primarily for
auto-indentation for code generation, but it also could be used to
remove whitespace (as a compression) from HTML output.  If you don't
care about indentation, you can simply implement <TT>write()</TT>:

<div class="code"><PRE>
public interface StringTemplateWriter {
    void pushIndentation(String indent);

    String popIndentation();

    void write(String str) throws IOException;
}
</PRE></div>



<P>Here is a "pass through" writer that is already defined:

<div class="code"><PRE>
/** Just pass through the text */
public class NoIndentWriter extends AutoIndentWriter {
    public NoIndentWriter(Writer out) {
        super(out);
    }

    public void write(String str) throws IOException {
	    out.write(str);
    }
}
</PRE></div>



<P>Use it like this:

<div class="code"><PRE>
StringWriter out = new StringWriter();
StringTemplateGroup group =
                new StringTemplateGroup("test");
group.defineTemplate("bold", "&lt;b&gt;$x$&lt;/b&gt;");
StringTemplate nameST = new StringTemplate(group, "$name:bold(x=name)$");
nameST.setAttribute("name", "Terence");
// write to 'out' with no indentation
nameST.write(new NoIndentWriter(out));
System.out.println("output: "+out.toString());
</PRE></div>



<P>Instead of using <TT>nameST.toString()</TT>, which calls <TT>write</TT> with a string write and returns its value, manually invoke <TT>write</TT> with your writer.

<P>If you want to always use a particular output filter, then use

<div class="code"><PRE>
StringTemplateGroup.setStringTemplateWriter(Class userSpecifiedWriterClass);
</PRE></div>



<P>The <TT>StringTemplate.toString()</TT> method is sensitive to the group's
writer class.
<H3>Auto-indentation</H3>


<P><TT>StringTemplate</TT> has auto-indentation on by default.  To turn it off,
use <TT>NoIndentWriter</TT> rather than (the default) <TT>AutoIndentWriter</TT>.

<P>At the simplest level, the indentation looks like a simple column count:

<div class="code"><PRE>
My dogs' names 
  $names; separator="\n"$
The last, unindented line
</PRE></div>



<P>will yield output like:

<div class="code"><PRE>
My dog's names
  Fido
  Rex
  Stinky
The last, unindented line
</PRE></div>



<P>where the last line gets "unindented" after displaying the list.  <TT>StringTemplate</TT> tracks the characters to the left of the <TT>$</TT> or <TT>&lt;</TT> rather than the column number so that if you indent with tabs versus spaces, you'll get the same indentation in the output.

<P>When there are nested templates, <TT>StringTemplate</TT> tracks the combined
indentation:

<div class="code"><PRE>
// &lt;user&gt; is indented two spaces
main(user) ::= &lt;&lt;
Hi
\t$user:quote(); separator="\n"$
&gt;&gt;

quote ::= " '$it$'"
</PRE></div>



<P>In this case, you would get output like:

<div class="code"><PRE>
Hi
\t 'Bob'
\t 'Ephram'
\t 'Mary'
</PRE></div>



<P>where the combined indentation is tab plus space for the attribute
references in template <TT>quote</TT>.  Expression <TT>$user$</TT> is indented by 1 tab and hence any attribute
generated from it (in this case the <TT>$attr$</TT> of <TT>quote()</TT>) must have
at least the tab.

<P>Consider generating nested statement lists as in C.  Any statements
inside must be nested 4 spaces.  Here are two templates that could
take care of this:

<div class="code"><PRE>
function(name,body) ::= &lt;&lt;
void $name$() $body$
&gt;&gt;

slist(statements) ::= &lt;&lt;
{
    $statements; separator="\n"$
}&gt;&gt;
</PRE></div>



<P>Your code would create a <TT>function</TT> template instance and an <TT>slist</TT>
instance, which gets passed to the <TT>function</TT> template as attribute
<TT>body</TT>.  The following Java code:

<div class="code"><PRE>
StringTemplate f = group.getInstanceOf("function");
f.setAttribute("name", "foo");
StringTemplate body = group.getInstanceOf("slist");
body.setAttribute("statements", "i=1;");
StringTemplate nestedSList = group.getInstanceOf("slist");
nestedSList.setAttribute("statements", "i=2;");
body.setAttribute("statements", nestedSList);
body.setAttribute("statements", "i=3;");
f.setAttribute("body", body);
</PRE></div>



<P>should generate something like:

<div class="code"><PRE>
void foo() {
    i=1;
    {
        i=2;
    }
    i=3;
}
</PRE></div>



<P>Indentation can only occur at the start of a line so indentation is
only tracked in front of attribute expressions following a newline.

<P>The one exception to indentation is that naturally, <TT>$if$</TT> actions do
not cause indentation as they do not result in any output.  However,
the subtemplates (THEN and ELSE clauses) will see indentations.  For
example, in the following template, the two subtemplates are indented
by exactly 1 space each:

<div class="code"><PRE>
     $if(foo)$
 $x$
\t\t$else
 $y$
$endif$
</PRE></div>


<H2>Examples</H2>


<P>You should look at
<TT>org.antlr.stringtemplate.test.TestStringTemplate.java</TT>, which
contains a many tests.
<H3>Fill-a-Table Example</H3>


<P>The manner in which a template engine handles filling an HTML table
with data often provides good insight into its programming and design
strategy.  It illustrates the interaction of the model and view via
the controller.  Using <TT>StringTemplate</TT>, the view may not access the
model directly; rather the view is the passive recipient of data from
the model.

<P>First, imagine we have objects of type <TT>User</TT> that we will pull from a
simulated database:

<div class="code"><PRE>
public static class User {
    String name;
    int age;
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
}
</PRE></div>



<P>Our database is just a static list:

<div class="code"><PRE>
static User[] users = new User[] {
    new User("Boris", 39),
    new User("Natasha", 31),
    new User("Jorge", 25),
    new User("Vladimir", 28)
};
</PRE></div>



<P>Here is my simple overall page design template, <TT>page.st</TT>:

<div class="code"><PRE>
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;$title$&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;$title$&lt;/h1&gt;

$body$

&lt;/body&gt;
&lt;/html&gt;
</PRE></div>



<P>The body attribute of <TT>page.st</TT> will be set to the following template
<TT>users.inline.st</TT> by my web server infrastructure (part of the controller):

<div class="code"><PRE>
&lt;table border=1&gt;
$users:{
  &lt;tr&gt;
    &lt;td&gt;$it.name$&lt;/td&gt;&lt;td&gt;$it.age$&lt;/td&gt;
  &lt;/tr&gt;
}$
&lt;/table&gt;
</PRE></div>



<P>Again, <TT>it</TT> is the default attribute passed to a template when you
apply that template to an attribute or attributes.  <TT>it.name</TT> gets
the <TT>name</TT> property, if it exists, from the <TT>it</TT> object ala
JavaBeans.  That is, <TT>StringTemplate</TT> uses reflection to call the
<TT>getName()</TT> method on the incoming object.  By using reflection, I
avoid a type dependence between model and view.

<P>Now, imagine the server and templates are set up to format data.  My
page definition is part of the controller that pulls data from the
model (the database) and pushes into the view (the template).  That is
all the page definition should do--interpret the data and set some
attributes in the view.  The view only formats data and does no
interpretation.

<div class="code"><PRE>
public static class UserListPage extends SamplePage {
    /** This "controller" pulls from "model" and pushes to "view" */
    public void generateBody(StringTemplate bodyST) throws Exception {
        User[] list = users; // normally pull from database
        // filter list if you want here (not in template)
        bodyST.setAttribute("users", list);
    }

    public String getTitle() { return "User List"; }
}
</PRE></div>



<P>Notice that the controller and model have no HTML in them at all and
that the template has no code with side-effects or logic that can
break the model-view separation.  If you wanted to only see users with
age &lt; 30, you would filter the list in <TT>generateBody()</TT> rather than
alter your template.  The template only displays information once the
controller pulls the right data from the model.

<P>Pushing factorization further, you could make a <TT>row.st</TT> component in
order to reuse the table row HTML:

<div class="code"><PRE>
&lt;tr&gt;
  &lt;td&gt;$it.name$&lt;/td&gt;&lt;td&gt;$it.age$&lt;/td&gt;
&lt;/tr&gt;
</PRE></div>



<P>Then the user list template reduces to the more readable:

<div class="code"><PRE>
&lt;table border=1&gt;
$users:row()$
&lt;/table&gt;
</PRE></div>



<P>Naturally, you could go one step further and make another component
for the entire table (putting it in file <TT>table.st</TT>):

<div class="code"><PRE>
&lt;table border=1&gt;
$elements:row()$
&lt;/table&gt;
</PRE></div>



<P>then the body template would simply be:

<div class="code"><PRE>
$table(elements=users)$
</PRE></div>


<H3>Internationalization and localization</H3>


<P>StringTemplate provides a simple and effective method for localizing
web pages.  The goal is to alter a page based upon the locale; that
is, page strings or other content must change depending on a locale.
This article not only illustrates how to make a pages change text
depending on locale, it shows how the same site may easily have two
different <em>skins</em> (site "looks").

<P>This technique works well in practice for real sites.  
<A HREF="http://demo.schoolloop.com/""><B> Schoolloop.com</B></A> is a case
in point.  Click on the link that says "<em>en espanol</em>" to flip the
site into Spanish mode.  The exam same templates are used; all strings
are pulled from a serious of resource bundles.  There is no
duplication of pages to change the strings.
<H4>Multiple skins</H4>


<P>First let's look at multiple skins in order to show how templates are
loaded for this example.

<P>Multiple site looks are organized into their own directories.  A
<TT>StringTemplateGroup</TT> object rooted at that directory will load
templates directly from there.  In my example, I made two skins, blue
and red.  Here is how the group is loaded:

<div class="code"><PRE>
String skin="blue";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// get a template group rooted at appropriate skin
String absoluteSkinRootDirectoryName = cl.getResource(skin).getFile();
StringTemplateGroup templates =
    new StringTemplateGroup("test", absoluteSkinRootDirectoryName);
</PRE></div>



<P>Then, when you ask for an instance of a page, it pulls from whichever
directory <TT>skin</TT> is set to:

<div class="code"><PRE>
StringTemplate page1ST = templates.getInstanceOf("page1");
</PRE></div>



<P>Here is page 1 in the  <font color=blue>blue</font>  skin:

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;$strings.page1_title$&lt;/title&gt;
&lt;body&gt;
&lt;font color=blue&gt;
&lt;p&gt;$strings.intro$

&lt;p&gt;$strings.page1_content$
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>



<P>and here is page 2:

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;$strings.page2_title$&lt;/title&gt;
&lt;body&gt;
&lt;font color=blue&gt;
&lt;p&gt;$strings.page2_content$
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>



<P>For the  <font color=red>red</font>  here is page 1:

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;$strings.page1_title$&lt;/title&gt;
&lt;body&gt;
&lt;font color=red&gt;
&lt;h1&gt;$strings.page1_title$&lt;/h1&gt;

&lt;p&gt;$strings.intro$
&lt;hr&gt;
&lt;p&gt;$strings.page1_content$
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>



<P>and page 2:

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;$strings.page2_title$&lt;/title&gt;
&lt;body&gt;
&lt;font color=red&gt;
&lt;h1&gt;$strings.page2_title$&lt;/h1&gt;
&lt;hr&gt;
&lt;p&gt;$strings.page2_content$
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>



<P>The thing to note is that there is no text, just formatting in these
page templates.  Those strings from the <TT>strings</TT> attribute are
used for all text that could change per locale.
<H4>Localizing template strings</H4>


<P>Once the code knows how to load templates, the locale must dictate
which strings are displayed.  The templates clearly have attribute
references pulling from a strings table (a hash table).  For this
example, I'm assuming that I have a few different strings and that I'm
storing them in a Java properties file called
<em>language</em><TT>.strings</TT> where <em>language</em> is the
two-letter language code.  Here is my <TT>en.strings</TT> file:

<div class="code"><PRE>
intro=Welcome to my test page for internationalization with StringTemplate
page1_title=Page 1 testing I18N
page2_title=Page 2 testing I18N
page1_content=This is page 1's simple page content
page2_content=This is page 2's simple page content
</PRE></div>



<P>and here is my <TT>fr.strings</TT> file:

<div class="code"><PRE>
intro=Bienvenue sur la page de test d'internationalisation avec StringTemplate
page1_title=Page 1 test de I18N
page2_title=Page 2 test de I18N
page1_content=Le contenu de la page 1
page2_content=Le contenu de la page 2
</PRE></div>



<P>To load these per the current locale is pretty easy:

<div class="code"><PRE>
// use Locale to get 2 letter country code for this computer
Locale locale = Locale.getDefault();
String defaultLanguage = locale.getLanguage();
// allow them to override language from argument on command line
String language = defaultLanguage;
if ( args.length&gt;0 ) {
    language = args[0];
}
// load strings from a properties files like en.strings
URL stringsFile = cl.getResource(language+".strings");
if ( stringsFile==null ) {
    System.err.println("can't find strings for language: "+language);
    return;
}
Properties strings = new Properties();
InputStream is = stringsFile.openStream();
strings.load(is);
</PRE></div>



<P>The <TT>strings</TT> properties object is just a <TT>Hashtable</TT> so
you can directly pass to StringTemplate templates as an attribute:

<div class="code"><PRE>
StringTemplate page1ST = templates.getInstanceOf("page1");
page1ST.setAttribute("strings", strings);
</PRE></div>



<P>To generate the page, just say:

<div class="code"><PRE>
System.out.println(page1ST);
</PRE></div>



<P>The output will be (for the <TT>en</TT> locale):

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;Page 1 testing I18N&lt;/title&gt;
&lt;body&gt;
&lt;font color=blue&gt;
&lt;p&gt;Welcome to my test page for internationalization with
StringTemplate

&lt;p&gt;This is page 1's simple page content
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>



<P>If I change the locale to <TT>fr</TT> then without changes templates,
the following is generated:

<div class="code"><PRE>
&lt;html&gt;
&lt;title&gt;Page 1 test de I18N&lt;/title&gt;
&lt;body&gt;
&lt;font color=blue&gt;
&lt;p&gt;

&lt;p&gt;Le contenu de la page 1
&lt;/font&gt;
&lt;/body&gt;
&lt;html&gt;
</PRE></div>


<H4>Source and compilation</H4>


<P>Here is the Java code, different strings, and different skins:
<UL>
<LI><A HREF="i18n/Test.java"><B> Test.java</B></A>
</LI>
<LI><A HREF="i18n/en.strings"><B> English strings</B></A>
</LI>
<LI><A HREF="i18n/fr.strings"><B> French strings</B></A>
</LI>
<LI><A HREF="i18n/blue/"><B> the blue skin</B></A>
</LI>
<LI><A HREF="i18n/red/"><B> the red skin</B></A>
</LI>

</UL>

<P>You naturally need ANTLR too; <A HREF="http://www.antlr.org/download.html"><B>
get it here</B></A>.

<P>You can compile this example like this:

<div class="code"><PRE>
javac -classpath .:antlr-2.7.6.jar:stringtemplate-2.3.jar Test.java
java -classpath .:antlr-2.7.6.jar:stringtemplate-2.3.jar Test
</PRE></div>


<H4>Summary</H4>


<P>In summary, the key element to demonstrate here is that you do not
have to duplicate all of your templates to change what they say.  You
can leave the formatting alone and, with a simple hashtable pulled
from a data file, push in the proper strings per the locale.  I also
took the opportunity to show off just how easy it is to make multiple
site skins.
<H2>StringTemplate Grammar</H2>


<P><TT>StringTemplate</TT> has multiple grammars that describe templates at
varying degrees of detail.  At the grossest level of granularity, the
<TT>group.g</TT> grammar accepts a list of templates with formal template
arguments.  Each of these templates is broken up into chunks of
literal text and attribute expressions via <TT>template.g</TT>.  The default
lexer uses <TT>$...$</TT> delimiters, but the <TT>angle.bracket.template.g</TT>
lexer provides <TT>&lt;...&gt;</TT> delimiters.  Each of the attribute expression
chunks is processed by <TT>action.g</TT>.  It builds trees (ASTs)
representing the operation indicated in the expression.  These ASTs
represent the "precompiled" templates, which are evaluated by the tree
grammar <TT>eval.g</TT> each time a <TT>StringTemplate</TT> is rendered to string
with <TT>toString()</TT>.

<P>The grammar files are:
<UL>
<LI><TT>group.g</TT>: read a group file full of templates
</LI>
<LI><TT>template.g</TT>: break an individual template into chunks
</LI>
<LI><TT>angle.bracket.template.g</TT>: <TT>&lt;...&gt;</TT> template lexer
</LI>
<LI><TT>action.g</TT>: parse attribute expressions into ASTs
</LI>
<LI><TT>eval.g</TT>: evaluate expression ASTs during <TT>toString()</TT>
</LI>

</UL>

<P>Anything outside of the <TT>StringTemplate</TT> start/stop delimiters is
ignored.

<P>A word about Strings.  Strings are double-quoted with optional
embedded escaped characters that are translated (escapes are not
translated outside of strings; for example, text outside of attribute
expressions do not get escape chars translated except <TT>\\$</TT>, <TT>\\&lt;</TT> and
<TT>\\&gt;</TT>).

<div class="code"><PRE>
STRING
    :   '"' (ESC_CHAR | ~'"')* '"'
    ;
</PRE></div>



<P>The translated escapes are:

<div class="code"><PRE>
ESC_CHAR
    :   '\\'
        (   'n'
        |   'r'
        |   't'
        |   'b'
        |   'f'
        |   '"'
        |   '\\'
        )
     ;
</PRE></div>



<P>but other escapes are allowed and ignored.

<P>Please see the actual grammar files for the formal language
specification of <TT>StringTemplate</TT>'s various components.
<H2>A Common Syntax Question</H2>


<P>Why have a template like:
 

<div class="code"><PRE>
Check this faq entry: $link(url="/faq/view?ID="+id, title="A FAQ")$.
</PRE></div>



<P>instead of 

<div class="code"><PRE>
Check this faq entry: $link(url="/faq/view?ID="+$id$, title="A FAQ")$.
</PRE></div>



<P>using <TT>$id$</TT> instead of <TT>id</TT> for that attribute reference?  The
simplest answer is that you are already within the scope of an
attribute expression between the <TT>$...$</TT> and hence <TT>StringTemplate</TT>
knows that <TT>id</TT> must be a reference to an attribute by the grammar
alone.  The template delimiters mark the beginning and end of what
<TT>StringTemplate</TT> cares about.

<P>Another way to look at it is the following.  Surely syntax (i) makes
the most sense:

<P>(i)   <TT>SELECT $col+blort$ FROM $table$</TT>

<P>(ii)  <TT>SELECT $$col$+$blort$$ FROM $table$</TT>

<P>(iii) <TT>SELECT $col$+$blort$ FROM $table$</TT>

<P>Syntax (ii) is rather verbose and redundant wouldn't you say?  Syntax
(iii) doesn't even work because the + is outside the realm of
<TT>StringTemplate</TT> delimiters.
<H2>Acknowledgements</H2>


<P>Tom Burns (CEO jGuru.com) co-designed <TT>StringTemplate</TT> and listened to
me think out loud incessantly.  I would also like to thank Monty
Zukowski for planting the <TT>template</TT> "meme" in my head back in the mid
1990's.  Loring Craymer and Monty both helped me hone these ideas for
use in source-to-source language translation.  Matthew Ford has done a
huge amount of thinking about StringTemplate and has submitted
numerous suggestions and patches.  Anthony Casalena at
<A HREF="http://www.squarespace.com"><B>http://www.squarespace.com</B></A> has been a big help beta-testing
<TT>StringTemplate</TT>.  Thanks to the users who have submitted suggestions,
bugs, sample code, etc...
</BODY>
</HTML>
